# 保留必要导入
import ctypes
import winreg
import os
import sqlite3
import subprocess
import time
import shutil

def disable_password_saving():
    """仅禁用密码保存功能"""
    try:
        # 增加ARM64架构注册表访问
        reg_settings = [
            (winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Edge\PasswordManager", [("PasswordSaveAllowed", 0)]),
            (winreg.HKEY_CURRENT_USER, r"Software\WOW6432Node\Microsoft\Edge\PasswordManager", [("PasswordSaveAllowed", 0)])
        ]

        for hive, subkey, values in reg_settings:
            try:
                with winreg.CreateKey(hive, subkey) as key:
                    for name, value in values:
                        winreg.SetValueEx(key, name, 0, winreg.REG_DWORD, value)
            except PermissionError:
                ctypes.windll.shell32.ShellExecuteW(None, "runas", "python", __file__, None, 1)
                
        print("已永久禁用密码保存功能")
        
        # 新增状态验证
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Edge\PasswordManager") as key:
            if winreg.QueryValueEx(key, "PasswordSaveAllowed")[0] != 0:
                print("警告：密码保存功能锁定失败")
    except Exception as e:
        print(f"注册表修改失败: {str(e)}")

def check_password_records():
    """检测是否存在已保存的密码"""
    try:
        local_appdata = os.getenv('LOCALAPPDATA')
        edge_data_dir = os.path.join(local_appdata, "Microsoft", "Edge", "User Data")
        
        for profile in os.listdir(edge_data_dir):
            if profile in ["System Profile", "Guest Profile", "Default"]:
                continue
                
            login_path = os.path.join(edge_data_dir, profile, "Login Data")
            if os.path.exists(login_path):
                with sqlite3.connect(login_path) as conn:
                    count = conn.execute("SELECT COUNT(*) FROM logins").fetchone()[0]
                    if count > 0:
                        return True
        return False
    except Exception as e:
        print(f"记录检测异常: {str(e)}")
        return False

def clear_saved_passwords():
    """仅清理已保存的密码"""
    try:
        # 终止Edge进程的逻辑适用于所有版本（v44+）
        subprocess.call(["taskkill", "/F", "/IM", "msedge.exe", "/IM", "msedgewebview2.exe", "/T"], 
                      stdout=subprocess.DEVNULL,
                      stderr=subprocess.DEVNULL)
        # 用户数据目录结构自Chromium 80+保持稳定
        edge_data_dir = os.path.join(os.getenv('LOCALAPPDATA'), "Microsoft", "Edge", "User Data")
        
        # 密码存储机制自2019年起未改变
        for profile in os.listdir(edge_data_dir):
            login_data_path = os.path.join(edge_data_dir, profile, "Login Data")
            if os.path.exists(login_data_path):
                try:
                    with sqlite3.connect(login_data_path) as conn:
                        conn.execute("DELETE FROM logins")  # 核心表结构保持向后兼容
                        conn.commit()
                        conn.execute("VACUUM")
                except Exception as e:
                    print(f"清理{profile}密码数据失败: {str(e)}")

        print("已清除所有保存的密码")
    except Exception as e:
        print(f"密码清理失败: {str(e)}")

def get_os_version():
    """获取操作系统版本信息"""
    try:
        reg_path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion"
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path) as key:
            product_name = winreg.QueryValueEx(key, "ProductName")[0]
            display_version = winreg.QueryValueEx(key, "DisplayVersion")[0]
            return f"{product_name} (版本 {display_version})"
    except Exception as e:
        import platform
        return f"{platform.platform()} (通过备用方式获取)"

def get_edge_version():
    """获取Microsoft Edge浏览器版本"""
    try:
        # 扩展注册表检测路径
        reg_paths = [
            # 常规安装路径
            (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A37A7E33}"),
            (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A37A7E33}"),
            # ARM64架构路径
            (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A37A7E33}"),
            # 企业版可能使用的路径
            (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft Edge"),
        ]
        
        for hive, path in reg_paths:
            try:
                with winreg.OpenKey(hive, path) as key:
                    # 尝试多种可能的版本字段
                    for field in ["pv", "version", "DisplayVersion"]:
                        try:
                            version, _ = winreg.QueryValueEx(key, field)
                            return version.split(".")[0]  # 返回主版本号
                        except FileNotFoundError:
                            continue
            except FileNotFoundError:
                continue
        
        # 备用方案：通过文件版本检测
        edge_path = os.path.join(os.getenv("PROGRAMFILES(X86)"), "Microsoft", "Edge", "Application", "msedge.exe")
        if os.path.exists(edge_path):
            info = subprocess.check_output(["powershell", f"(Get-Item '{edge_path}').VersionInfo.FileVersion"], shell=True)
            return info.decode().strip().split('.')[0]
            
        return "未知版本（请手动验证）"
    except Exception as e:
        print(f"版本检测失败: {str(e)}")
        return "检测异常"

if __name__ == "__main__":
    if ctypes.windll.shell32.IsUserAnAdmin():
        # 新增系统信息显示
        print(f"当前操作系统: {get_os_version()}")
        print(f"当前Edge版本: {get_edge_version()}")
        # 新增预检测
        print("\n检测密码保存功能状态...")
        if check_password_records():
            print("⚠️ 发现已保存的密码记录")
        else:
            print("✅ 未发现密码记录")
            
        disable_password_saving()
        clear_saved_passwords()
        
        # 清理后验证
        print("\n最终验证：")
        print(f"密码保存功能状态: {'❌ 启用' if check_password_records() else '✅ 禁用'}")
        input("操作完成，按回车退出...")
    else:
        ctypes.windll.shell32.ShellExecuteW(None, "runas", "python", __file__, None, 1)